import rclpy
from rclpy.node import Node
import requests
from example_interfaces.msg import String
from queue import Queue



class GfPyTopicPublishNode(Node):
    def __init__(self,node_name:str):

        self.topic="gf_novel"
        self.qos=10

        super().__init__(node_name=node_name)
        self.novel_queue=Queue()
        self.novel_publisher=self.create_publisher(
            msg_type=String,
            topic=self.topic,
            qos_profile=self.qos
        )
        self.timer=self.create_timer(1,self.timer_callback)
        self.finished=False

    def download_novel(self,url):
        response=requests.get(url)
        if response.status_code==200:
            self.novel_queue.put(response.text)
            self.get_logger().info("下载小说成功")
            for line in response.text.split("\n"):
                self.novel_queue.put(line)
        else:
            self.get_logger().error("下载小说失败")
        self.finished=True
    def timer_callback(self):
        if self.novel_queue.qsize()>0:
            msg=String()
            msg.data=self.novel_queue.get()
            self.novel_publisher.publish(msg)
            self.get_logger().info(f"发布小说成功:{msg.data}")
        elif self.finished:
            self.get_logger().info("小说下载完成")
            quit()

def main():
    rclpy.init()
    node=GfPyTopicPublishNode(node_name="gf_py_topic")
    node.download_novel("http://192.168.1.28:8000/novel01.txt")
    rclpy.spin(node)
    rclpy.shutdown()